import csv
import os
from loguru import logger as log

def write_to_csv(file_path, data, header=None):
    """
    将数据写入CSV文件

    参数:
    file_path (str): 输出文件路径
    data (list): 包含字典或列表的数据集
    header (list, optional): CSV文件的表头
    """
    file_exists = os.path.exists(file_path)
    with open(file_path, 'a+', newline='', encoding='utf-8-sig') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=header)
        if not file_exists:
            writer.writeheader()
        writer.writerows(data)
    log.info(f"成功写入CSV文件: {file_path}")


if __name__ == "__main__":
    # 示例1：写入字典数据（带表头）
    file_path1 = "example1.csv"
    data1 = [
        {"姓名": "张三", "年龄": 25, "城市": "北京"},
        {"姓名": "李四", "年龄": 30, "城市": "上海"},
        {"姓名": "王五", "年龄": 28, "城市": "广州"}
    ]
    header1 = ["姓名", "年龄", "城市"]
    write_to_csv(file_path1, data1, header1)